//! @Author: DengLibin
//! @Date: Create in 2023-11-06 15:08:30
//! @Description: 全局配置

use std::fmt::Display;

use rust_common::mysql::MysqlClient;
use serde::{Deserialize, Serialize};

#[derive(Debug)]
pub struct GlobalError {
    pub msg: String,
}
impl std::fmt::Display for GlobalError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.msg)
    }
}

// 自定义结果
pub type GlobalResult<T> = std::result::Result<T, GlobalError>;

//转换结果
pub fn check_result<T, E: Display>(result: Result<T, E>) -> GlobalResult<T> {
    return match result {
        Ok(r) => Result::Ok(r),
        Err(err) => Result::Err(GlobalError {
            msg: err.to_string(),
        }),
    };
}

//接口响应数据格式
#[derive(Debug, Serialize, Deserialize)]
pub struct Resdata<T> {
    pub status_code: i16,
    pub status_msg: String,
    pub data: Option<T>,
}

impl<T> Resdata<T> {

    pub fn ok_result(result: GlobalResult<T>) -> Self {
        return match result {
            Ok(t) => Resdata {
                status_code: 200,
                status_msg: "".into(),
                data: Some(t),
            },
            Err(err) => Resdata {
                status_code: -1,
                status_msg: err.to_string(),
                data: None,
            },
        };
    }
}

//共享状态
pub struct AppState {
    pub mysql_client: MysqlClient,
}
